
import network from '../api/index'
import { ElMessage, ElLoading } from 'element-plus'
import { ref, getCurrentInstance } from 'vue'
import { useStore } from '../store/index'
import { tr } from 'element-plus/es/locales.mjs'
const { communityApi,
    userApi,
    request } = network
export default function usePost() {
    // 加载帖子列表
    const page = ref(1)
    const pageSize = 5
    const store = useStore()
    const { proxy } = getCurrentInstance()
    const user = store.getUserInfo()
    const loadLock = ref(false)
    const loading = ref(false)
    const displayedPosts = ref([])
    const searchQuery = ref('')
    const tag = ref('')
    const loadPosts = async (isUserList = false) => {
        try {
            loading.value = true
            loadLock.value = false
            const res = await request(isUserList ? communityApi.getUserPostList : communityApi.getCommunityList, ({
                page: page.value,
                pageSize: pageSize,
                userId: user.id,
                search: searchQuery.value,
                tag: tag.value
            }))
            if (!res.data.pagination.hasMore) {
                // 加载锁定
                loadLock.value = true
            }
            displayedPosts.value = res.data.data.map(post => ({
                ...post,
                created_at: proxy.$formatDateTime(post.created_at, {
                    relative: true,
                    format: 'yyyy年MM月dd日 HH时mm分'
                })
            }))
        } catch (error) {
            console.log(error)
            ElMessage.error('加载帖子失败')
        } finally {
            loading.value = false
        }
    }
    const handleLike = async (post) => {
        try {
            const data = {
                postId: post.postId,
                userId: user.id
            }
            const res = await request(communityApi.likePost, data, 'post')
            loadPosts()
            ElMessage.success('点赞成功')

        } catch (error) {
            ElMessage.warning(error)
        }
    }
    return {
        displayedPosts,
        searchQuery,
        tag,
        loadLock,
        loading,
        page,
        pageSize,
        user,
        loadPosts,
        handleLike
    }
}